package gateway;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
@Configuration
public class RestTemplateConfig {

    @Bean("restTemplate10")
    public RestTemplate restTemplate(@Qualifier("requestFactory10") OkHttp3ClientHttpRequestFactory requestFactory) {
        return buildRestTemplate(requestFactory);
    }

    @Bean("requestFactory10")
    public OkHttp3ClientHttpRequestFactory requestFactory(@Qualifier("okHttpClient10") OkHttpClient okHttpClient) {
        addShutdownHook(okHttpClient);
        return new OkHttp3ClientHttpRequestFactory(okHttpClient);
    }


    @Bean("okHttpClient10")
    public OkHttpClient okHttpClient(ConnectionPool connectionPool) {
        return new OkHttpClient().newBuilder().connectionPool(connectionPool).connectTimeout(5, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    @Bean
    public ConnectionPool connectionPool() {
        int maxIdleConnections = 30;
        return new ConnectionPool(maxIdleConnections, 5, TimeUnit.MINUTES);
    }

    private RestTemplate buildRestTemplate(OkHttp3ClientHttpRequestFactory requestFactory) {
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        messageConverters.remove(1);
        StringHttpMessageConverter messageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        messageConverter.setWriteAcceptCharset(false);
        messageConverters.add(1, messageConverter);
        return restTemplate;
    }

    private void addShutdownHook(OkHttpClient okHttpClient) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            ConnectionPool connectionPool = okHttpClient.connectionPool();
            connectionPool.evictAll();
            ExecutorService executorService = okHttpClient.dispatcher().executorService();
            executorService.shutdown();
            try {
                executorService.awaitTermination(3, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
            }
        }, "OkHttpShutDownHook"));
    }
}
